/**
 * @Author : ZiQin Zhai
 * @Date : 2019/6/4 10:14
 * @Version : 1.0
 * @Last Modifined by : ZiQin Zhai
 * @Last Modifined time : 2019/6/4 10:14
 * @Description 路由模型
 * */
import { createMenu } from './MenuModel';

class JeRouter {
  constructor({
    path, name, component, title, icon, meta, isShow, children = [], redirect, keepAlive = false,
  }) {
    this.path = path;
    this.name = name || `router-${path}-${title}`;
    this.component = component;
    this.redirect = redirect;
    this.meta = {
      ...meta,
      title,
      icon,
      isShow: !!isShow,
      keepAlive,
    };
    this.children = children;
    this.childName = []; // 子功能名称
  }

  /**
   * 获取当前视图下的菜单项目
   * @returns {Array}
   */
  getMenu() {
    const menu = [];
    const { children } = this;
    if (Array.isArray(children)) {
      children.forEach((item) => {
        menu.push(createMenu({
          title: item.meta.title,
          icon: item.meta.icon,
          isShow: item.meta.isShow,
          path: item.path,
        }));
      });
    }
    return menu;
  }

  /**
   * 增加子元素
   */
  addChild(child) {
    let normailzeChild = Array.isArray(child) ? child : [child];
    normailzeChild = normailzeChild.filter(item => !this.childName.includes(`${item.name}-plugin`)).map((item) => {
      item.name += '-plugin';
      this.childName.push(item.name);
      return item;
    });
    if (JE.isEmpty(this.children)) {
      this.children = normailzeChild;
    } else {
      this.children.push(...normailzeChild);
    }
  }
}

/**
 * factory function
 * @param path 路由路径
 * @param name 路由名称
 * @param component 路由地址
 * @param title 标题
 * @param icon 菜单图标
 * @param isShow 是否显示
 * @param children 子路由信息
 * @param keepAlive 是否缓存
 * @returns {Router}
 */
function createRouter({
  path, name, component, title, icon, isShow, children, redirect, keepAlive, meta,
}) {
  return new JeRouter(...arguments);
}

export default createRouter;
